package com.itheima;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Jwttest {

    @Test
    public void testJwt() {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", "1");
        claims.put("username", "张三");

        //生成jwt
        String token =  JWT.create()
                .withClaim("username", claims)//添加自定义信息
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))//设置过期时间
                .sign(Algorithm.HMAC256("itheima"));//指定算法，配置密钥

        System.out.println(token);
    }


    @Test
    public void testParse(){
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6eyJpZCI6IjEiLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3Mjg4NDY4NTB9.Zb2NhSviQcoh8efrwNnoDYWACiJZa6Ud5Fk6pQUIIcQ";
        //创建jwt验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("itheima")).build();
        //验证token,生成一个解密后的jwt对象
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        //获取自定义信息
        Map<String, Claim> claims = decodedJWT.getClaims();
        System.out.println(claims.get("user"));
    }
}
